package com.tiancheng.trade.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiancheng.trade.commom.core.data.PageInfo;
import com.tiancheng.trade.payment.enums.ChannelRefundTypeEnum;
import com.tiancheng.trade.payment.enums.FlowStatusEnum;
import com.tiancheng.trade.payment.mapper.IntFlowDetailMapper;
import com.tiancheng.trade.payment.mapper.IntRefundFlowDetailMapper;
import com.tiancheng.trade.payment.model.IntFlowDetail;
import com.tiancheng.trade.payment.model.IntRefundFlowDetail;
import com.tiancheng.trade.payment.service.IntFlowDetailService;
import com.tiancheng.trade.payment.service.SettleMatchService;
import com.tiancheng.trade.payment.util.helper.PaymentIdHelper;
import com.tiancheng.trade.payment.vo.api.PaypalCreateReqVO;
import com.tiancheng.trade.payment.vo.api.QueryFlowDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 英文版支付流水明细业务接口实现
 */
@Slf4j
@Service
public class IntFlowDetailServiceImpl implements IntFlowDetailService {

    @Resource
    private IntFlowDetailMapper intFlowDetailMapper;
    @Resource
    private IntRefundFlowDetailMapper intRefundFlowDetailMapper;
    @Resource
    private SettleMatchService settleMatchService;

    @Override
    public int save(String flowId, String paymentId, PaypalCreateReqVO paypalCreateReqVO) {
        List<IntFlowDetail> flowDetails = new ArrayList<>();
        int subFlowInc = 1; // 子订单流水起始值
        for (PaypalCreateReqVO.SubOrderPaypalDTO subOrder : paypalCreateReqVO.getSubPaypalOrders()) {
            IntFlowDetail intFlowDetail = new IntFlowDetail();
            intFlowDetail.setFlowId(flowId);
            intFlowDetail.setPaymentId(paymentId);
            intFlowDetail.setSubOrderId(subOrder.getSubOrderId());
            intFlowDetail.setMerchantCode(subOrder.getMerchantCode());
            intFlowDetail.setMerchantName(subOrder.getMerchantName());
            intFlowDetail.setProductCode(subOrder.getProductCode());
            intFlowDetail.setProductId(subOrder.getProductId());
            intFlowDetail.setProductName(subOrder.getProductName());
            intFlowDetail.setProductCount(subOrder.getProductCount());
            intFlowDetail.setProductDetail(subOrder.getProductDetail());
            intFlowDetail.setOrderAmount(subOrder.getOrderAmount());
            intFlowDetail.setAmount(subOrder.getAmount());
            intFlowDetail.setCurrency(paypalCreateReqVO.getCurrency());
            // 子订单流水
            intFlowDetail.setSubOrderFlowId(PaymentIdHelper.getSubOrderFlowId(flowId,  subFlowInc));
            flowDetails.add(intFlowDetail);
            subFlowInc++;
        }
        return intFlowDetailMapper.save(flowDetails);
    }

    @Override
    public PageInfo find(QueryFlowDetailVO queryFlowDetailVO) {
        if (queryFlowDetailVO.getEndTime() == null) {
            queryFlowDetailVO.setEndTime(LocalDateTime.now());
        }
        if (queryFlowDetailVO.getStartTime() == null) {
            queryFlowDetailVO.setStartTime(queryFlowDetailVO.getEndTime().minusMonths(1).withHour(0).withMinute(0).withSecond(0));
        }

        IPage<Map> page = intFlowDetailMapper.find(queryFlowDetailVO,
                new Page<>(queryFlowDetailVO.getCurrent(), queryFlowDetailVO.getSize()));
        return intFlowDetailMapper.convertPage(page);
    }

    /**
     * 流水明细批量更新-所更新字段值相同
     *
     * @param ids       id
     * @param colValMap 字段-值：(column, value)
     * @return
     */
    @Override
    public int updateSettleBatch(List<Long> ids, Map<String, Object> colValMap) {
        return intFlowDetailMapper.updateSettleBatch(ids, colValMap);
    }

    @Override
    public List<IntFlowDetail> findByFlowId(String flowId) {
        if (StringUtils.isEmpty(flowId)) {
            return null;
        }
        QueryWrapper<IntFlowDetail> conditions = new QueryWrapper<>();
        conditions.eq("flow_id", flowId);
        return intFlowDetailMapper.selectList(conditions);
    }

    /**
     * 修改退款明细表状态
     * @param paymentId
     * @param subOrderId
     * @param refundType
     * @param flowStatusEnum
     * @return
     */
    @Override
    public Integer updateRefundStatus(String paymentId, String subOrderId,
                                      ChannelRefundTypeEnum refundType, FlowStatusEnum flowStatusEnum) {
        QueryWrapper<IntRefundFlowDetail> conditions = new QueryWrapper<>();
        conditions.eq("payment_id", paymentId);
        if(refundType.getCode().equals(ChannelRefundTypeEnum.SPLIT.getCode())){
            Assert.isTrue(StringUtils.isNotEmpty(subOrderId), "未查询到相应退款流水");
            // 部分退款
            conditions.eq("sub_order_id", subOrderId);
        }
        IntRefundFlowDetail entity = new IntRefundFlowDetail();
        entity.setRefundStatus(flowStatusEnum.getCode());
        return intRefundFlowDetailMapper.update(entity,conditions);
    }

    @Override
    public int updateAmount(String flowId, Integer couponAmount) {
        List<IntFlowDetail> flowDetails = this.findByFlowId(flowId);
        if (!CollectionUtils.isEmpty(flowDetails) && null != couponAmount && couponAmount > 0) {
            log.info("更新流水优惠信息：flowId：{}， couponAmount：{}",flowId,couponAmount);
            //总订单金额
            try {
//                BigDecimal sumOrderAmount = flowDetails.stream().map(IntFlowDetail::getOrderAmount).
//                        reduce(BigDecimal.ZERO, BigDecimal::add);
                int sumOrderAmount = flowDetails.stream().mapToInt(IntFlowDetail::getOrderAmount).sum();
                //BigDecimal discountTotal = new BigDecimal(0.00);
                int discountTotal =0;
                for (int i = 0; i < flowDetails.size(); i++) {
                    IntFlowDetail flowDetail = flowDetails.get(i);
                    IntFlowDetail updateDetail = new IntFlowDetail();
                    QueryWrapper<IntFlowDetail> conditions = new QueryWrapper<>();
                    conditions.eq("id", flowDetails.get(i).getId());
                    conditions.eq("flow_id", flowId);
                    if (i == flowDetails.size() - 1) {
                        //updateDetail.setAmount(flowDetail.getOrderAmount().subtract(discountTotal));
                        updateDetail.setAmount(flowDetail.getOrderAmount()-discountTotal);
                    } else {
                        // 1、计算子订单所占总金额的比例，小数点后取10位，然后截取
                        // 2、总优惠金额*子订单比例，然后四舍五入取整
                      /*  int divide = flowDetail.getOrderAmount().
                                divide(sumOrderAmount, 10, BigDecimal.ROUND_DOWN)
                                .multiply(BigDecimal.valueOf(couponAmount)).setScale(0, BigDecimal.ROUND_UP).intValue();
                        updateDetail.setAmount(flowDetail.getOrderAmount()-divide);
                        discountTotal += divide;*/
                    }
                    intFlowDetailMapper.update(updateDetail, conditions);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("更新流水优惠异常：{}",e.getMessage());
            }
        }
        return 0;
    }

    @Override
    public List<IntFlowDetail> selectList(QueryWrapper<IntFlowDetail> condition) {
        return intFlowDetailMapper.selectList(condition);
    }

}
